<template>
  <div class="container">
    <el-card>
      <div slot="header">
        {{ this.$route.query.id ? "试题修改" : "试题录入" }}
      </div>
      <el-form
        ref="questionsForm"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            @change="changeSubjectID"
            v-model="form.subjectID"
            style="width: 400px"
          >
            <el-option
              v-for="item in subjuectsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="form.catalogID" style="width: 400px">
            <el-option
              v-for="item in directorysList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="form.enterpriseID" style="width: 400px">
            <el-option
              v-for="item in companysList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="province">
          <el-select
            @focus="getProvince"
            @change="getCitys"
            v-model="form.province"
            style="width: 198px; margin-right: 4px"
          >
            <el-option
              v-for="(item, index) in provincesList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-select v-model="form.city" style="width: 198px">
            <el-option
              v-for="(item, index) in citysList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select style="width: 400px" v-model="form.direction">
            <el-option
              v-for="(item, index) in directionList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="form.questionType" @change="changeOptions">
            <el-radio
              v-for="(item, index) in questionTypeList"
              :key="index"
              :label="item.value"
              >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio
            v-model="form.difficulty"
            v-for="(item, index) in difficultyList"
            :key="index"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-form-item>
        <el-form-item label="题干：" prop="question">
          <quillEditor :options="editorOption" v-model="form.question" />
        </el-form-item>
        <el-form-item
          label="选项："
          prop="options"
          v-if="form.questionType !== 3"
        >
          <div
            class="options"
            v-for="(item, index) in form.options"
            :key="index"
          >
            <el-radio-group
              @change="changeRadio"
              v-model="optionValue"
              v-if="form.questionType === 1"
              style="padding: 15px 0"
            >
              <el-radio
                v-model="form.options.code"
                :label="item.code"
                style="margin-right: 0px"
                >{{ item.code }}：</el-radio
              >
            </el-radio-group>
            <el-checkbox-group
              v-model="optionValueList"
              @change="changeCheckbox"
              v-if="form.questionType === 2"
            >
              <el-checkbox :label="item.code" style="margin-right: 0px"
                >{{ item.code }}：</el-checkbox
              >
            </el-checkbox-group>
            <el-input v-model="item.title" style="width: 240px"></el-input>
            <el-upload
              v-model="item.img"
              class="avatar-uploader"
              action="http://geek.itheima.net/v1_0/upload"
              name="image"
              :show-file-list="false"
              :on-success="
                (res, file) => {
                  uploadSuccess(item, res, file);
                }
              "
              :on-error="uploadError"
              :before-upload="beforeUpload"
            >
              <img :src="item.img" v-if="item.img" class="avatar" />
              <span class="text" v-else @click="getImgIndex(index)"
                >上传图片</span
              >
            </el-upload>
            <i class="el-icon-circle-close" @click="removeImg(item)"></i>
          </div>
          <el-button
            type="danger"
            size="small"
            :disabled="form.questionType !== 2"
            @click="addoptions"
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <el-form-item label="解析视频：" prop="videoURL">
          <el-input v-model="form.videoURL" style="width: 400px" />
        </el-form-item>
        <el-form-item label="答案解析：" prop="answer">
          <quillEditor :options="editorOption" v-model="form.answer" />
        </el-form-item>
        <el-form-item label="题目备注：" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            :rows="3"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item label="试题标签" prop="tags">
          <el-select
            multiple
            v-model="form.tags"
            style="width: 400px"
            placeholder="请选择试题标签"
          >
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            :type="this.$route.query.id ? 'success' : 'primary'"
            @click="onSubmit"
            >{{ this.$route.query.id ? "确认修改" : "确认提交" }}</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
// 实现代码高亮的两个文件
import hljs from "highlight.js";
import "highlight.js/styles/monokai-sublime.css";

import { simple as subjuectsList } from "@/api/hmmm/subjects";
import { simple as directorysList } from "@/api/hmmm/directorys";
import { simple as tagsList } from "@/api/hmmm/tags";
import { list as companysList } from "@/api/hmmm/companys";
import { provinces, citys } from "@/api/hmmm/citys";
import { direction, questionType, difficulty } from "@/api/hmmm/constants";
import {
  add as addQuestionsNew,
  detail as questionsDetail,
  update as updateQuestions,
} from "@/api/hmmm/questions";
export default {
  name: "aa",
  components: { quillEditor },
  data() {
    return {
      // 副文本配置项
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
            [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
            ["blockquote", "code-block"], // 引用  代码块
            ["image", "link"], // 链接、图片、视频
          ],
          // 语法高亮
          syntax: {
            highlight: (text) => hljs.highlightAuto(text).value,
          },
        },
        placeholder: "",
      },
      form: {
        // 表单绑定数据
        subjectID: "", // 学科
        catalogID: "", // 目录
        enterpriseID: "", // 企业
        province: "", // 城市
        city: "", // 地区
        direction: "", // 方向

        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: "", //题干
        options: [
          // 选项
          { code: "A", title: "", img: "", isRight: 0 },
          { code: "B", title: "", img: "", isRight: 0 },
          { code: "C", title: "", img: "", isRight: 0 },
          { code: "D", title: "", img: "", isRight: 0 },
        ],
        videoURL: "", //解析视频
        answer: "", //答案解析
        remarks: "", //题目备注
        tags: "", //标签
      },
      rules: {
        subjectID: [
          { trigger: "change", message: "请选择学科", required: true },
        ],
        catalogID: [
          { trigger: "change", message: "请选择目录", required: true },
        ],
        enterpriseID: [
          { trigger: "change", message: "请选择企业", required: true },
        ],
        province: [
          { trigger: "change", message: "请选择城市", required: true },
        ],
        city: [{ trigger: "change", message: "请选择地区", required: true }],
        direction: [
          { trigger: "change", message: "请选择方向", required: true },
        ],
        questionType: [
          { trigger: "change", message: "请选择题型", required: true },
        ],
        difficulty: [
          { trigger: "change", message: "请选择难度", required: true },
        ],
        question: [
          { trigger: "change", message: "请输入题干", required: true },
        ],
        answer: [
          { trigger: "change", message: "请输入答案解析", required: true },
        ],
      },
      subjuectsList: [], // 学科
      directorysList: [], // 目录
      tagsList: [], // 标签
      companysList: [], //企业
      provincesList: [], // 市
      citysList: [], //地区
      directionList: [], // 方向
      optionValue: "", //单选选项
      optionValueList: [], //多选选项列表
      questionTypeList: [], //题型
      difficultylist: [], // 难度
      imageIndex: "", // 选项图片index
      imgURl:'',
    };
  },
  created() {
    this.getSubjuectsList(); // 学科列表
    this.getCompanysList(); // 企业列表

    this.directionList = direction; // 方向列表
    this.questionTypeList = questionType; //题型
    this.difficultyList = difficulty; // 难度
    // 路由有参数id时,调用获取基础题库列表,回写数据
    if (this.$route.query.id) {
      this.questionsDetail();
    }
  },
  methods: {
    // 学科简单列表
    async getSubjuectsList() {
      const { data } = await subjuectsList();
      this.subjuectsList = data;
    },
    // 点击学科
    changeSubjectID() {
      this.getDirectorysList();
      this.getTagsList();
    },
    // 目录列表
    async getDirectorysList() {
      const { data } = await directorysList({ subjectID: this.form.subjectID });
      this.directorysList = data;
    },
    // 标签
    async getTagsList() {
      const { data } = await tagsList({ subjectID: this.form.subjectID });
      this.tagsList = data;
    },
    // 企业列表
    async getCompanysList() {
      const {
        data: { items },
      } = await companysList({ pagesize: 99 });
      this.companysList = items;
    },
    // 市√
    getProvince() {
      this.provincesList = provinces();
    },
    // 地区√
    getCitys(provinces) {
      this.citysList = citys(provinces);
    },
    // 添加选项
    addoptions() {
      this.form.options.push({
        code: String.fromCharCode("A".charCodeAt(0) + this.form.options.length),
        title: "",
        img: "",
        isRight: 0,
      });
    },
    // 获取图片选项index
    getImgIndex(index) {
      this.imageIndex = index;
    },
    // 上传成功
 
    uploadSuccess(item, res, file) {
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      // item.img = URL.createObjectURL(file.raw);
      // console.log(111, res, file);
      item.img = res.data.url;
    },
    // 上传失败
    uploadError(err) {
      this.$message.error("上传失败");
    },
    // 上传前检查
    beforeUpload(file) {
      // 检查文件类型
      const types = ["image/jpeg", "image/gif", "image/bmp", "image/png"];
      if (!types.find((item) => item === file.type)) {
        this.$message.error("上传图片只能是 JPG、GIF、BMP、PNG 格式!");
        return false;
      }
      // 检查图片大小
      const maxSize = 1024 * 1024 * 5;
      if (file.size > maxSize) {
        this.$message.error("图片大小最大不能超过5M");
        return false;
      }
      return true; // 上传成功
    },
    // 改变题型
    changeOptions() {
      this.optionValue = "";
      this.optionValueList = [];
    },
    // 单选
    changeRadio(val) {
      this.form.options.forEach((item) => {
        if (item.code === val) {
          item.isRight = 1;
        } else {
          item.isRight = 0;
        }
      });
    },
    // 多选
    changeCheckbox(val) {
      this.form.options.forEach((item) => {
        val.forEach((i) => {
          if (item.code === i) {
            item.isRight = 1;
          }
        });
      });
    },
    removeImg(item){
      // console.log(item);
      item.img = ''
    },
    // 提交
    async onSubmit() {
      // 手动校验
      await this.$refs.questionsForm.validate();
      if (this.$route.query.id) {
        // 试题修改
        await updateQuestions({
          ...this.form,
          id: +this.$route.query.id,
          questionType: this.form.questionType.toString(),
          difficulty: this.form.difficulty.toString(),
          tags: this.form.tags.toString(),
        });
          this.$router.push("/questions/list");
        this.$message.success("修改成功");
      } else {
        // 试题录入
        await addQuestionsNew({
          ...this.form,
          questionType: this.form.questionType.toString(),
          difficulty: this.form.difficulty.toString(),
          tags: this.form.tags.toString(),
        });
        this.$router.push("/questions/list");
        this.$message.success("添加成功");
      }
    },
    // 基础题库详情
    async questionsDetail() {
       const { data } = await questionsDetail({ id: this.$route.query.id });
     
      
      data.options.forEach((item) => {
        if (data.questionType === '1') {
          if (item.isRight === 1) {
            item.checked = true;
            this.optionValue = item.code;
          }
        }else if (data.questionType === '2'){

              if (item.isRight === 1) {
            item.checked = true;
            this.optionValueList = item.code
          }
        }
      })
      
      this.form = {
        // 表单绑定数据
        subjectID: data.subjectID || "", // 学科id
        catalogID: data.catalogID || "", // 目录id
        enterpriseID: data.enterpriseID || "", // 企业
        province: data.province || "", // 城市
        city: data.city || "", // 地区
        direction: data.direction || "", // 方向
        questionType: +data.questionType || 1, // 题型
        difficulty: +data.difficulty || 1, // 难度
        question: data.question || "", // 题干
        options: data.options || [
          // 选项
          { code: "A", title: "", img: "", isRight: 0 },
          { code: "B", title: "", img: "", isRight: 0 },
          { code: "C", title: "", img: "", isRight: 0 },
          { code: "D", title: "", img: "", isRight: 0 },
        ],
        videoURL: data.videoURL || "", // 解析视频
        answer: data.answer || "", // 答案解析
        remarks: data.remarks || "", // 题目备注
        tags: data.tags.split(",") || "", // 标签, 字符串转换为数组,以,分割
      };
      const res = await directorysList({ subjectID: data.subjectID });
      this.directorysList = res.data
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0);
      });
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 20px;

  .quill-editor {
    height: 200px;
    margin-bottom: 50px;
  }
  .options {
    padding-bottom: 20px;
    position: relative;
    .el-checkbox-group {
      display: inline-block;
    }
    i {
      position: absolute;
      right: 627px;

      top: -11px;
      background: #fff;
      font-size: 18px;
      color: #999;
      z-index: 1;
    }
      
  }
   

  .avatar-uploader {
    display: inline-block;
    vertical-align: middle;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    width: 100px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    margin-left: 4px;

    &:hover {
      border-color: #409eff;
    }

    .avatar {
      width: 100px;
      height: 60px;
      background-size: contain;
    }

    .text {
      display: inline-block;
      font-size: 14px;
      width: 100px;
      height: 60px;
    }

    
  }
}
</style>
